from typing import Optional, List
from pathlib import Path


def _check_page_out(func):
    """
    漫画章数、话数、页数检查器（闭包）

    :param func: 被检测的生成章数或话数或页数的函数
    :return:
    """
    def temp_func(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except (KeyError, IndexError) as e:
            return []

    return temp_func


class Comic_Gen:
    """
    漫画列表生成器
    """
    __slots__ = ['__chapter',
                 '__word',
                 '__base_path',
                 '__like_json_dict',
                 ]
    __instance = None

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance

    def __init__(self,
                 chapter: Optional[str] = 'EP1',
                 word: Optional[str] = '1'):
        self.__chapter = chapter
        self.__word = word
        self.__base_path = Path(__file__).parent.parent / Path('static/data/neko')
        self.__like_json_dict = {}
        self.__init_json_dict()

    def __init_json_dict(self):
        for chapter in self.__base_path.iterdir():
            word_temp = {}
            for word in (self.__base_path / Path(f'{chapter.name}')).iterdir():
                word_temp[word.name] = []
                for pic in (self.__base_path / Path(f'{chapter.name}/{word.name}')).iterdir():
                    word_temp[word.name].append(pic)
            self.__like_json_dict[chapter.name] = word_temp

    def get_chapter_list(self) -> List[str]:
        """
        获取章节

        :return: 章节字符串列表
        """
        return sorted(self.__like_json_dict.keys(), key=lambda x: len(x))

    @_check_page_out
    def get_word_list(self, chapter: str) -> List[str]:
        """
        获取对应章节的话数

        :param chapter: 对应章节
        :return: 话字符串列表
        """
        return sorted(self.__like_json_dict[chapter].keys(), key=lambda x: len(x))

    @_check_page_out
    def get_pic_url(self, chapter: str, word: str) -> List[Path]:
        """
        获取对应章对应话的所有图片

        :param chapter: 对应章
        :param word: 对应话
        :return: 图片Path对象列表
        """
        return self.__like_json_dict[chapter][word]


if __name__ == '__main__':
    from pprint import pprint
    import sys

    c = Comic_Gen()
    pprint(sys.getsizeof(c))
    pprint(c.get_chapter_list())
    pprint(c.get_word_list('海猫鸣泣之时 翼'))
